package com.mrzhou.mybatis.base;

import com.baomidou.mybatisplus.autoconfigure.MybatisPlusProperties;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mrzhou.core.tool.api.CloudUser;
import com.mrzhou.core.tool.constants.CloudConstant;
import com.mrzhou.core.tool.utils.Func;
import com.mrzhou.mybatis.support.Condition;
import com.mrzhou.web.util.WebUtil;
import org.springframework.beans.factory.annotation.Autowired;

import java.time.LocalDateTime;

public class BaseServiceImpl<M extends BaseMapper<T>, T extends BaseEntity> extends ServiceImpl<M, T> implements IBaseService<T> {

    @Autowired
    private MybatisPlusProperties properties;

    @Override
    public boolean save(T entity) {
        CloudUser user = WebUtil.getUser();
        if(null != user) {
            entity.setCreateDept(user.getDeptId());
            entity.setCreateUser(user.getUserId());
            entity.setUpdateUser(user.getUserId());
        }
        // 保存插入时的时间
        LocalDateTime now = LocalDateTime.now();
        entity.setCreateTime(now);
        entity.setUpdateTime(now);

        if(null == entity.getStatus()) {
            // 如果没有设置status, 则默认为1
            entity.setStatus(CloudConstant.DEFAULT_STATUS_VALUE);
        }
        // 使用参数列表配置的
        entity.setIsDelete(this.getLogicNotDeleteValue());
        return super.save(entity);
    }

    @Override
    public boolean updateById(T entity) {
        return super.updateById(entity);
    }

    @Override
    public boolean saveOrUpdate(T entity) {
        // 更新用户信息
        CloudUser cloudUser = WebUtil.getUser();
        if (null != cloudUser) {
            entity.setUpdateTime(LocalDateTime.now());
            entity.setUpdateUser(cloudUser.getUserId());
        }
        return super.saveOrUpdate(entity);
    }

    /**
     * 自定义分页方法
     * @param page 分页查询
     * @return
     */
    @Override
    public IPage<T> page(PageQuery page) {
        return super.page(new Page<>(page.getCurrent(), page.getSize()), Condition.getQueryWrapper(page,null));
    }

    /**
     * 获取mybatis-plus配置的逻辑删除
     * @return
     */
    private Integer getLogicNotDeleteValue() {
        return Func.toInt(properties.getGlobalConfig().getDbConfig().getLogicNotDeleteValue());
    }

}
